package springinpractice.ch4.r4_5.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/*
 * Author       :       Willie Wheeler and John Wheeler
 * Book         :       'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */

// Best practice: Avoid using HibernateDaoSupport and HibernateTemplate
// See http://static.springframework.org/spring/docs/2.5.5/api/org/springframework/orm/hibernate3/HibernateTemplate.html
// See http://blog.springsource.com/main/2007/06/26/so-should-you-still-use-springs-hibernatetemplate-andor-jpatemplate/
// See http://forum.springframework.org/showthread.php?p=190042#post190042
// See http://forum.springframework.org/showthread.php?t=27009
public abstract class HbnAbstractDao<T extends Object> implements AbstractDao<T> {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	private Class<T> domainClass;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@SuppressWarnings("unchecked")
	private Class<T> getDomainClass() {
	    if (domainClass == null) {
	    	ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();
	        this.domainClass = (Class<T>) thisType.getActualTypeArguments()[0];
	    }
	    return domainClass;
	}
	
	private String getDomainClassName() {
		return getDomainClass().getName();
	}
	
	public void save(T t) {
		getSession().save(t);
	}
	
	@SuppressWarnings("unchecked")
	public T load(Long id) {
		return (T) getSession().load(getDomainClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getList() {
		Query q = getSession().createQuery("from " + getDomainClassName());
		return q.list();
	}
	
	public void update(T t) {
		getSession().update(t);
	}
	
	public void delete(T t) {
		getSession().delete(t);
	}
	
	public void deleteById(Long id) {
		getSession().delete(load(id));
	}
	
	public void deleteAll() {
		Query q = getSession().createQuery("delete " + getDomainClassName());
		q.executeUpdate();
	}
	
	public int count() {
		Query q = getSession()
			.createQuery("select count(*) from " + getDomainClassName());
		return (Integer) q.list().get(0);
	}
}
